package com.warm.androidstudy.http;

import android.os.Environment;
import android.os.SystemClock;

import com.warm.androidstudy.config.ConfigConstant;
import com.warm.androidstudy.service.RetrofitApiService;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitManager {
    private static RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private RetrofitApiService retrofitApiService;
//    private OkHttpClient okHttpClient = OkHttpUtil.getInstance().getInitOkHttpClient();
    private OkHttpClient okHttpClient;


    private RetrofitManager() {
        initOkHttpClient();
        initRetrofit();
    }

    public static RetrofitManager getInstance(){

        if (retrofitManager==null){
            synchronized (RetrofitManager.class){
                if (retrofitManager==null){
                    retrofitManager = new RetrofitManager();
                }
            }
        }
        return retrofitManager;
    }

    public static RetrofitApiService getApiService(){
        return retrofitManager.retrofitApiService;
    }
    private void initRetrofit(){

        retrofit = new Retrofit.Builder()
                .baseUrl(ConfigConstant.DEFAULT_SERVER_DEBUG)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build();
    }


    public <T>  T createApi(String ShowUrl,Class<T> service){
        T t=retrofit.create(service);
        return t;
    }


    private void initOkHttpClient() {

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// 包含header、body数据
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

//http数据log，日志中打印出HTTP请求&响应数据

        if (okHttpClient==null){
            okHttpClient = new OkHttpClient.Builder()
                    //设置缓存文件路径，和文件大小
                    .cache(new Cache(new File(Environment.getExternalStorageDirectory() + "/okhttp_cache/"), 50 * 1024 * 1024))
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .addInterceptor(new HttpLoggingInterceptor())
                    .addInterceptor(loggingInterceptor)
                    //设置在线和离线缓存
//                .addInterceptor(OfflineCacheInterceptor.getInstance())
//                .addNetworkInterceptor(NetCacheInterceptor.getInstance())
                    .build();
        }
    }
}
